﻿using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

namespace NetTrafficStatistics
{
	class DataTable : Panel
	{
		public DataTable (ArrayList arr, Tools.Units u, string dtt)
		{
			var h = 0;
			var w = new[] { 3, Tools.DateWidth + 3, Tools.DateWidth + Tools.DataWidth + 3 };

			foreach (ArrayList r in (ArrayList) arr[0])
			{
				h += Tools.Step;
				for (var i = 0; i < 3; i++)
				{
					string t;
					Font font;
					if (i == 0)
					{
						font = Tools.Fb;
						var d = DateTime.Parse (r[i].ToString());
						t = GetDateTime (d, dtt);
					}
					else
					{
						font = Tools.F;
						var v = (long) r[i];
						t = GetValue (v, u);
						var m = ((long[]) arr[2])[i];

						// Add ProgressBar
						var pb = new ProgressBarT
			         	{
							Maximum = (int) (m > Int32.MaxValue ? Int32.MaxValue : m),
							Value = (int) (v > Int32.MaxValue ? Int32.MaxValue : v),
			         		Top = h + 2,
			         		Height = 10,
			         		Left = w[i] + 80,
			         		Width = 80
			         	};
						Controls.Add (pb);
					}

					var l = new Label
		        	{
		        		Text = t,
		        		Top = h,
		        		Left = w[i],
		        		AutoSize = true,
		        		Font = font,
		        	};
					Controls.Add (l);
				}
			}

			// Add Totals
			h += Tools.Step * 2;
			for (var i = 1; i < 3; i++)
			{
				var l = new Label
	        	{
	        		Text = GetValue (((long[]) arr[1])[i], u),
	        		Top = h,
	        		Left = w[i],
	        		AutoSize = true,
	        		Font = Tools.F,
	        		BackColor = Color.LightGray
	        	};
				Controls.Add (l);
			}

			Height = h + Tools.Step;
		}

		
		private static string GetValue (double v, Tools.Units u)
		{
			switch (u)
			{
				case Tools.Units.B:
					break;

				case Tools.Units.KB:
					v = v / 1024;
					break;

				case Tools.Units.MB:
					v = v / 1048576;
					break;

				case Tools.Units.GB:
					v = v / 1073741824;
					break;
			}

			return v.ToString ("###,##0.##");
		}

		public static string GetDateTime (DateTime time, string type)
		{
			switch (type)
			{
				case "HH:00":
					return time.ToString ("HH:00") + time.AddHours (1).ToString ("-HH:00");

				default:
					return time.ToString (type);
			}
		}
	}
}
